package com.dragee.utils.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.dragee.config.exception.BusinessException;
import lombok.Getter;

import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Consumer;

/**
 * 基于EasyExcel的导入工具类，插入使用批量插入，BATCH_COUNT=500
 * @author pw
 * @param <T> 中间接收类
 */
@Getter
public class CommonListener<T> extends AnalysisEventListener<T> {
    /**
     *  执行的插入的service
     */
    private final Consumer<List<T>> p;
    /**
     * 字典
     */
    private final Map<String, Map<String,Object>> itemMap;
    /**
     * 中间类的字段
     */
    Field[] fields ;
    /**
     * 初始化参数，server 执行
     * @param itemMap 字典数据,从里面去对应的数据
     * @param p 执行方法
     */
    public CommonListener(Map<String,Map<String,Object>> itemMap,
                          Class<T> tClass,
                          Consumer<List<T>> p) {
        this.p = p;
        this.itemMap = itemMap;
        this.fields = tClass.getDeclaredFields();
    }
    /**
     * 批量插入数据的大小
     */
    private final int BATCH_COUNT = 500;
    /**
     * 存储数据的集合
     */
    private final List<T> rows = new ArrayList<>();
    /**
     * 存储数据的集合
     */
    private final Map<String, Set<String>> unique = new HashMap<>();
    /**
     * 存放失败的数据及原因
     */
    private final List<String> msgList = new ArrayList<>();

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            msgList.add(String.format("第%s行，第%s列解析异常，数据为:%s",excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(),excelDataConvertException.getCellData()));
        }
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        ReadRowHolder readRowHolder = context.readRowHolder();
        try {
            for ( Field field : fields )  {
                //得到属性值
                field.setAccessible(true);
                if (field.get(data) == null) {
                    continue;
                }
                String value = field.get(data).toString();
                if(field.isAnnotationPresent(FieldDispose.class)){
                    //获取字段注解
                    FieldDispose annotation = field.getAnnotation(FieldDispose.class);
                    switch (annotation.type()){
                        //字典替换
                        case DICT:
                            if(!itemMap.get(annotation.value()).containsKey(value)){
                                msgList.add(String.format("第%s行异常，原因%s，数据为:%s",
                                        readRowHolder.getRowIndex()+1,
                                        annotation.errorMessage(),
                                        value));
                                return;
                            }
                            field.set(data, itemMap.get(annotation.value()).get(value));
                            break;
                        //唯一值判断
                        case UNIQUE:
                            if(unique.containsKey(annotation.value())){
                                if(unique.get(annotation.value()).contains(value)){
                                    msgList.add(String.format("第%s行异常，原因%s，数据为:%s",
                                            readRowHolder.getRowIndex()+1,annotation.errorMessage(),
                                            value));
                                    return;
                                }
                            }else {
                                Set<String> m = new HashSet<>();
                                m.add(value);
                                unique.put(annotation.value(),m);
                            }
                            break;
                        default:break;
                    }
                }
            }
            rows.add(data);
            if(rows.size()>=BATCH_COUNT){
                this.saveBatch();
            }
        }catch (Exception e){
            msgList.add(String.format("第%s行异常，原因:%s",readRowHolder.getRowIndex()+1,e.getMessage()));
        }
    }

    /**
     * 数据解析完成执行
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(rows.size()>0){
            this.saveBatch();
        }
    }

    private void saveBatch(){
        try {
            p.accept(rows);
        }catch (BusinessException e){
            rows.clear();
            msgList.add(e.getMessage());
        }
    }
}